package com.gitee.liang521.generate.common.util;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.util.Map;

/**
 * @author liang zai
 * @date 2021/9/16 11:30
 * @description
 */
@Slf4j
@Component
public class SpringUtils {

    @Autowired
    private ApplicationContext context;

    @Autowired
    private Environment environment;

    /**
     * 获取 spring 项目的根目录
     * @return
     */
    @Nullable
    public String getRootPath(){
        try {
           return ResourceUtils.getURL("classpath:").getPath().replace("/target/classes/","");
        } catch (FileNotFoundException e) {
            log.info(e.getMessage());
            return null;
        }
    }

    /**
     *获取spring 项目启动类的包名
     * @return
     */
    @Nullable
    public String getRootPackage(){
        Map<String, Object> annotation = context.getBeansWithAnnotation(SpringBootApplication.class);
        return CollUtil.isEmpty(annotation.values()) ?
                annotation.values().toArray()[0].getClass().getPackage().getName() : null;
    }

}
